package news.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.orm.SugarRecord;
import com.whu.administrator.ws.R;
import com.whu.administrator.ws.UIHandler;

import java.util.ArrayList;
import java.util.List;

import inter.Delegate;
import inter.ResponseStatus;
import model.News;
import news.adapter.SimpleNotifyAdapter;
import news.dto.SimpleNotify;
import news.network.GetNewNotify;

/**
 * 新闻界面
 * Created by Administrator on 2016/3/23.
 */
public class NewsActivity extends UIHandler.BaseActivity{

    ListView lv_news;

    PullToRefreshListView pullToRefreshListView;

    List<SimpleNotify> simpleNotifies = new ArrayList<SimpleNotify>();
    SimpleNotifyAdapter simpleNotifyAdapter = new SimpleNotifyAdapter();
    {
        simpleNotifyAdapter.setSimpleNotifies(simpleNotifies);
    }


    GetNewNotify getNewNotify = new GetNewNotify();
    Delegate basicNew = new Delegate() {
        @Override
        public void onResponse(String response) {
            pullToRefreshListView.onRefreshComplete();
            if (!response.startsWith("{")) return;
            Gson gson = new Gson();
            GetNewNotify.ResponseNotify responseNotify = gson.fromJson(response, GetNewNotify.ResponseNotify.class);
            if (responseNotify.getStatus().equals(ResponseStatus.SUCCESS))
            {
                simpleNotifies.clear();
                for(List<String> tmp:responseNotify.getNotifyLists())
                {
                    SimpleNotify simpleNotifyTmp = new SimpleNotify(tmp.get(0),tmp.get(1),tmp.get(2),tmp.get(3),tmp.get(4));
                    simpleNotifies.add(simpleNotifyTmp);
                }
                simpleNotifyAdapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onErrorResponse(VolleyError error) {
            pullToRefreshListView.onRefreshComplete();
        }
    };


    // 新消息
    Delegate newNew = new Delegate() {
        @Override
        public void onResponse(String response) {
            pullToRefreshListView.onRefreshComplete();
            if (!response.startsWith("{")) return;
            Gson gson = new Gson();
            GetNewNotify.ResponseNotify responseNotify = gson.fromJson(response, GetNewNotify.ResponseNotify.class);
            if (responseNotify.getStatus().equals(ResponseStatus.SUCCESS))
            {
                if (responseNotify.getNotifyLists().isEmpty())
                {
                    Toast.makeText(NewsActivity.this,"已是最新",Toast.LENGTH_SHORT).show();
                    return;
                }

                int j = responseNotify.getNotifyLists().size() - 1;
                while (j >= 0)
                {
                    List<String> tmp = responseNotify.getNotifyLists().get(j);
                    SimpleNotify simpleNotifyTmp = new SimpleNotify(tmp.get(0),tmp.get(1),tmp.get(2),tmp.get(3),tmp.get(4));
                    simpleNotifies.add(0,simpleNotifyTmp);
                    j--;
                }

                simpleNotifyAdapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onErrorResponse(VolleyError error) {
            pullToRefreshListView.onRefreshComplete();
        }
    };

    // 以前的消息
    Delegate oldNew = new Delegate() {
        @Override
        public void onResponse(String response) {
            pullToRefreshListView.onRefreshComplete();
            if (!response.startsWith("{")) return;
            Gson gson = new Gson();
            GetNewNotify.ResponseNotify responseNotify = gson.fromJson(response, GetNewNotify.ResponseNotify.class);
            if (responseNotify.getStatus().equals(ResponseStatus.SUCCESS))
            {

                if (responseNotify.getNotifyLists().isEmpty())
                {
                    Toast.makeText(NewsActivity.this,"已没有其他数据",Toast.LENGTH_SHORT).show();
                    return;
                }
                for(List<String> tmp:responseNotify.getNotifyLists())
                {
                    SimpleNotify simpleNotifyTmp = new SimpleNotify(tmp.get(0),tmp.get(1),tmp.get(2),tmp.get(3),tmp.get(4));
                    simpleNotifies.add(simpleNotifyTmp);
                }
                simpleNotifyAdapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onErrorResponse(VolleyError error) {
            pullToRefreshListView.onRefreshComplete();
        }
    };

    // 请求
    GetNewNotify.RequestNotify requestNotify = new GetNewNotify.RequestNotify();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news);
        initview();
        initdata();
    }

    private void initdata() {

        List<SimpleNotify> simpleNotifiesTmp = getFromdb();
        simpleNotifies.addAll(simpleNotifiesTmp);
        simpleNotifyAdapter.notifyDataSetChanged();

        requestNotify.setIsNew("2");
        requestNotify.setNotify_ID("0");
        getNewNotify.setDelegate(basicNew);
        getNewNotify.setRequestNotify(requestNotify);
        getNewNotify.get();
    }

    private void initview() {

        pullToRefreshListView = (PullToRefreshListView) findViewById(R.id.id_refreshlistview);
        lv_news = pullToRefreshListView.getRefreshableView();
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        pullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                getNew();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                getMore();
            }
        });
        lv_news.setAdapter(simpleNotifyAdapter);
        lv_news.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                SimpleNotify simpleNotify = simpleNotifies.get(position - 1);
                Intent intent = new Intent(NewsActivity.this, DetailNewsActivity.class);
                intent.putExtra("notify_ID", simpleNotify.getNotify_ID());
                NewsActivity.this.startActivity(intent);
            }
        });

    }

    // 获取更多数据
    private void getMore() {
        if (simpleNotifies.isEmpty()) return;
        SimpleNotify simpleNotify = simpleNotifies.get(simpleNotifies.size()-1);
        requestNotify.setNotify_ID(simpleNotify.getNotify_ID());
        requestNotify.setIsNew("0");
        getNewNotify.setDelegate(oldNew);
        getNewNotify.get();
    }

    // 获取最新
    private void getNew() {
        if (simpleNotifies.isEmpty()) return;
        SimpleNotify simpleNotify = simpleNotifies.get(0);
        requestNotify.setNotify_ID(simpleNotify.getNotify_ID());
        requestNotify.setIsNew("1");
        getNewNotify.setDelegate(newNew);
        getNewNotify.get();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SugarRecord.deleteAll(News.class);
        save2db(simpleNotifies);
    }

    // 从数据库获取
    public List<SimpleNotify> getFromdb()
    {
        List<SimpleNotify> simpleNotifies = new ArrayList<SimpleNotify>();
        List<News> newses = SugarRecord.findWithQuery(News.class,"Select * from News limit 0,20");
        for (News news:newses)
        {
            SimpleNotify simpleNotify = new SimpleNotify();
            simpleNotify.setNotify_Title(news.getNotify_Title());
            simpleNotify.setNotify_Time(news.getNotify_Time());
            simpleNotify.setNotify_Digest(news.getNotify_Digest());
            simpleNotify.setNotify_Author(news.getNotify_Author());
            simpleNotify.setNotify_ID(news.getNotify_ID());
            simpleNotifies.add(simpleNotify);
        }

        return simpleNotifies;
    }

    // 保存到数据库
    public void save2db(List<SimpleNotify> simpleNotifies)
    {
        List<News> newses = new ArrayList<News>();
        for (SimpleNotify simpleNotify:simpleNotifies)
        {
            News news = new News();
            news.setNotify_ID(simpleNotify.getNotify_ID());
            news.setNotify_Author(simpleNotify.getNotify_Author());
            news.setNotify_Digest(simpleNotify.getNotify_Digest());
            news.setNotify_Time(simpleNotify.getNotify_Time());
            news.setNotify_Title(simpleNotify.getNotify_Title());
            newses.add(news);
        }
        SugarRecord.saveInTx(newses);
    }
}
